import importlib
import gc
import os
import sys
import importlib.util


def import_module_dynamically(module_name):
    if module_name in sys.modules:
        importlib.reload(sys.modules[module_name])
    else:
        return importlib.import_module(module_name)


gc.collect()


def generate_code():
    code = [
        "import os\n",
        "import sys\n",
        "import requests\n",
    ]
    code.append("def eee():\n")
    for j in range(1000):
        code.append(f"    a{j}={j}\n")
    return ''.join(code)


code = generate_code()
# 创建并导入模块
def create_import(i):
    global code
    code2=code+f"    print({i})"
    py_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ee", f"a{i}.py")
    with open(py_path, "w", encoding="utf-8") as f:
        f.write(code2)
    return py_path


try:
    os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), "ee"))
except FileExistsError:
    pass

sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "ee"))

i = 0
while True:
    i += 1
    p = create_import(i)
    module_name = f"ee.a{i}"

    spec = importlib.util.spec_from_file_location(module_name, p)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    mod.eee()

    if module_name in sys.modules:
        del sys.modules[module_name]

    os.remove(p)

    importlib.invalidate_caches()
    gc.collect()
